/*
 * TODO language 
 * Copyright (c) 2010 TODO Team
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include "internal/gc.h"

namespace todo {

/**
 * Objects pointer list
 */
gclist GCValue::list;

/**
 * GCValue constructor
 */
GCValue::GCValue(Value* val)
{
	gclist::iterator valptr;
	
	valptr = findPtr(val);
	
	if (valptr != list.end()) {
		++(*valptr)->refcount;
		addr = (*valptr)->ptr;
	} else {
		GCInfo* new_val = new GCInfo(val);
		
		list.push_front(new_val);
		addr = new_val->ptr;
	}
}

/**
 * GCValue destructor
 */
GCValue::~GCValue(void)
{
	gclist::iterator valptr = findPtr(addr);

	if ((*valptr)->refcount) {
		--(*valptr)->refcount;
	}
	if ((*valptr)->refcount == 0) {
		collect();
	}
}

/**
 * Free objects with refcount equal to zero
 */
void GCValue::collect(void)
{
	for (gclist::iterator it = list.begin(); it != list.end(); ++it) {
		if ((*it)->refcount == 0) {
			list.remove(*it);
		}
	}	
}

/**
 * Sets all objects with circular references to be freed
 */
void GCValue::shutdown(void)
{
	if (list.size() == 0) {
		return;
	}
	for (gclist::iterator it = list.begin(); it != list.end(); ++it) {
		(*it)->refcount = 0;
	}
	collect();
}

/**
 * Finds a pointer in the list
 */
gclist::iterator GCValue::findPtr(Value* val)
{
	gclist::iterator it = list.begin();
	
	for (; it != list.end(); ++it) {
		if ((*it)->ptr == val) {
			return it;
		}
	}
	return it;
}

} // todo
